<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/30/030
 * Time: 17:02
 */

namespace app\api\model;
use app\api\service\Product as ProductService;
use think\Image;

class Product extends BaseModel {
    protected $hidden = ['update_time','delete_time', 'create_time', 'status', 'delete', 'market_type', 'for_sale', 'category_id', 'brand_id'];

    /**
     * 产品文案
     * @return \think\model\relation\hasOne
     */
    public function productDetails() {
        return $this->hasOne('ProductDetails');
    }

    /**
     * 产品品牌
     * @return \think\model\relation\belongsTo
     */
    public function brand() {
        return $this->belongsTo('Brand');
    }

    /**
     * 产品分类
     * @return \think\model\relation\belongsTo
     */
    public function category() {
        return $this->belongsTo('Category');
    }

    /**
     * 产品图片
     * @return \think\model\relation\HasMany
     */
    public function images() {
        return $this->hasMany('ProductImage');
    }

    /**
     * 产品评价
     * @return \think\model\relation\hasMany
     */
    public function productComment() {
        return $this->hasMany('ProductComment');
    }

    /**
     * 获取器处理产品图片
     * @param $value
     * @return string
     */
    public function getImageAttr($value)
    {
        return get_img_url($value);
    }

    /**
     * 获取器处理产品缩略
     * @param $value
     * @return string
     */
    public function getThumbAttr($value)
    {
        return get_img_url($value);
    }

    /**
     * 根据配置信息获取首页产品数据
     * @return array
     */
    public static function getIndexProduct() {

        $index_data = System::get(['key' => 'entrance_index_page']);
        $index_data = json_decode($index_data['value'], true);

        $data = [];
        if ($index_data && is_array($index_data)) {
            foreach ($index_data as $key => $val) {
                $product = self::where('id', 'in', $val['ids'])
                    ->where('delete', 0)
                    ->where('status', 2)
                    ->select();

                $data[$key]['product'] = $product;
                $data[$key]['image'] = isset($val['image']) ? get_img_url($val['image']) : '';
            }
        }

        return $data;
    }


    /**
     * 根据 cid 和 key 获取产品列表
     * 可传入 sort 进行排序
     * @param $cid
     * @param $key
     * @param $sort
     * @return \think\Paginator
     */
    public static function getProductListByCidKey($cid, $key, $sort) {
        $for_sale = $key == 'is_shop' ? 2 : 1;

        $where = [
            ['category_id', '=', $cid],
            ['for_sale', '=', $for_sale],
            ['delete', '=', 0],
            ['status', '=', 2]
        ];

        // 排序
        $order = 'sort desc, id desc';

        if ($sort) {
            $order = str_replace("_"," ", $sort);
        }

        $product_list =  self::field('thumb, id, name, price, for_sale')
            ->where($where)
            ->order($order)
            ->paginate(8, true);

        return $product_list;
    }

    /**
     * 获取产品详情
     * @param $id
     * @param int $for_sale
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public static function getProductInfo($id, $for_sale = 0) {

        $where = [
            ['id', '=', $id],
            ['delete', '=', 0],
            ['status', '=', 2]
        ];
        if ($for_sale > 0) {
            // 兼容订单获取产品的时候，产品类型必须跟订单类型匹配
            $where[] = ['for_sale', '=', $for_sale];
        }
        $data = self::withCount('productComment')->with(['productDetails', 'images', 'brand', 'category'])->where($where)->find();
        if ($data) {
            // 商品图片
            if ($data['images']) {
                foreach ($data['images'] as $key => $val) {
                    // 有些老图片太大 处理一下
                    if (is_file('./' . $val['image'])) {
                        $image = Image::open('./' . $val['image']);
                        if ($image->width() > 750) {
                            $image->thumb(750, 750)->save($val['image']);
                        }
                    }
                }
            }

            // 初始化价格区间和产品属性组
            $price_scope  = '';
            $product_attr_group = [];

            // 销售商品和购买商品的属性数据需要分开获取
            if ($data['for_sale'] == 1) {
                $product_attr = ProductService::productCustomizationAttr($data);
            } else {
                $product_attr_data = ProductService::productMarketAttr($data);
                $product_attr = $product_attr_data['attr'];
                $price_scope = $product_attr_data['price_scope'];
                $product_attr_group = $product_attr_data['product_attr_group'];
            }

            $data['attr'] = $product_attr;
            $data['price_scope'] = $price_scope;
            $data['product_attr_group'] = $product_attr_group;
        }
        return $data;
    }

    /**
     * 返回产品所有属性，并且根据已选则的属性设置可选状态
     * @param $id
     * @param $select_ids
     * @return mixed
     */
    public static function getProductAttr($id, $select_ids) {

        $select_ids = explode(',', $select_ids);

        $where = [
            ['id', '=', $id],
            ['delete', '=', 0],
            ['status', '=', 2]
        ];

        $data = self::where($where)->find();
        $product_attr_data = ProductService::productMarketAttr($data);

        $product_attr = $product_attr_data['attr']; // 所有属性
        $product_attr_group = $product_attr_data['product_attr_group'];  // 所有属性组

        $attr_len = count($product_attr);  // 属性种类数量

        $return_data = [
            'product_attr' => [],
            'price' => 0,
            'inventory' => 0,
            'image' => '',
            'id' => 0
        ];

        if ($select_ids) {
            // 获取已选属性的数据
            $select_attr = [];
            foreach ($product_attr as $attr) {
                foreach ($attr['value'] as $v) {
                    if (in_array($v['id'], $select_ids)) {
                        $select_attr[] = $v;
                    }
                }
            }

            // 循环所有属性
            foreach ($product_attr as &$attr) {
                foreach ($attr['value'] as &$v) {
                    // 检查属性是否在以选择的集合中
                    if (!in_array($v['id'], $select_ids)) {
                        $id = $v['id'];
                        $ids = [];
                        foreach ($attr['value'] as $a) {
                            $ids[] = $a['id'];
                        }
                        $check_attr = self::check_data($id, $ids, $attr_len, $select_attr, $product_attr_group);
                        // 根据检查结果，设置属性是否可以被选择
                        $v['select'] = $check_attr;

                    } else {
                        // 在的话  已选则状态为true
                        $v['selected'] = true;
                    }
                }
            }

            if ($attr_len == count($select_ids)) {
                foreach ($product_attr_group as $group_item) {
                    $i = 0;
                    foreach ($select_attr as $s_attr) {
                        $s_id = (int)$s_attr['id'];
                        $array_keys = array_keys($group_item,$s_id);
                        if(in_array($s_id, $group_item) && $array_keys[0] < $attr_len) {
                            $i++;
                        }
                    }
                    if ($i == $attr_len) {
                        $return_data['price'] = $group_item[$attr_len];
                        $return_data['inventory'] = $group_item[$attr_len + 1];
                        $return_data['image'] = $group_item[$attr_len + 2];
                        $return_data['id'] = $group_item[$attr_len + 3];
                    }
                }
            }
        }
        $return_data['product_attr'] = $product_attr;

        return $return_data;
    }

    public static function check_data($id, $ids, $attr_len, $select_attr, $product_attr_group) {

        $id = (int)$id; //id转换成整型

        //获取选中的属性组合
        $check_ids = []; //初始化选中的id集合
        $select_group_name = [];

        //吧不是同组的选中元素加入数组中
        foreach ($select_attr as $s_attr) {
            if (!in_array($s_attr['id'], $ids)) {
                $check_ids[] = $s_attr['id'];
            }
            $select_group_nam[] = $s_attr['name'];
        }

        //初始化标记
        $i = 0;

        //循环产品拥有的属性组
        foreach ($product_attr_group as $group_item) {
            $array_keys = array_keys($group_item,$id);
            //检查元素是否在数组集合里面,由于索引从0开始，所以索引的位置必须小于属性种类数量，防止查找到价格，库存，图片等元素
            if(in_array($id, $group_item) && $array_keys[0] < $attr_len) {
                //如果在,则循环当前已选元素是否都在这个集合里面，如果都在则表示这个元素是可选的返回true，如果没在则表示这个原色跟已选择元素不搭，返回false，让它变成不可选
                $d = 0;
                if (count($check_ids) > 0) {
                    foreach ($check_ids as $check_id) {

                        $check_id = (int)$check_id;//id转换成整型
                        $array_keys = array_keys($group_item,$id);

                        // ...
                        if(in_array($check_id, $group_item) && $array_keys[0] < $attr_len) {
                            $d++;
                        }
                    }

                    if ($d == count($check_ids)) {
                        $i++;
                    }
                } else {
                    $i++;
                }
            }
        }

        if ($i > 0) {
            return true;
        } else {
            return false;
        }
    }
}